import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 102. 二叉树的层序遍历
 */
public class Solution_102 {
    /**
     * 二叉树的层序遍历
     * <p>
     * 时间复杂度：O(N)，N 为节点数
     * <p>
     * 空间复杂度：O(N)，N 为节点数
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            // 获取当前队列长度，即二叉树这一层的节点数
            int size = queue.size();
            // 临时存储当前层节点值
            List<Integer> temp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                temp.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            ans.add(temp);
        }
        return ans;
    }

    public static void main(String[] args) {
        Solution_102 solution = new Solution_102();
        TreeNode root = new TreeNode(3);
        TreeNode left = new TreeNode(9);
        TreeNode right = new TreeNode(20, new TreeNode(15), new TreeNode(7));
        root.left = left;
        root.right = right;
        List<List<Integer>> ans = solution.levelOrder(root);
        System.out.println(ans);
    }
}
